package cube.io.file;

import java.io.Closeable;
import java.io.IOException;

/**
 * 文件处理
 * 
 * @author abiao
 */
public abstract class FileHandler<Stream extends Closeable, Result> {

    /**
     * 文件名
     */
    private String fileName;

    private Stream stream;

    public FileHandler(String fileName) {
        this.fileName = fileName;
    }

    /**
     * 文件流处理
     */
    public Result handle() {
        Result result = null;
        stream = init(fileName);
        try {
            result = execute(stream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        close(stream);
        return result;
    }

    /**
     * 关闭流
     */
    protected void close(Closeable stream) {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化流
     */
    protected abstract Stream init(String fileName);

    /**
     * 对流执行操作
     */
    public abstract Result execute(Stream stream) throws Exception;
}
